package com.unionpay.upyzt.example;

import com.unionpay.upyzt.Upyzt;
import com.unionpay.upyzt.exception.UpyztException;
import com.unionpay.upyzt.model.GuaranteeConfirm;
import com.unionpay.upyzt.resp.GuaranteeConfirmResp;

import java.time.OffsetDateTime;
import java.util.HashMap;
import java.util.Map;

public class GuaranteeConfirmExample {

    private final String guaranteePaymentId;

    public GuaranteeConfirmExample(String guaranteePaymentId) {
        this.guaranteePaymentId = guaranteePaymentId;
    }

    /**
     * 运行 Demos
     *
     * @param guaranteePaymentId 担保下单ID
     * @return 担保确认ID
     */
    public static String runDemos(String guaranteePaymentId) throws UpyztException {
        GuaranteeConfirmExample guaranteeConfirmExample = new GuaranteeConfirmExample(guaranteePaymentId);

        // 担保确认
        GuaranteeConfirmResp guaranteeConfirmResp = guaranteeConfirmExample.create();

        // 担保确认订单查询（系统订单号）
        guaranteeConfirmResp = guaranteeConfirmExample.retrieveById(guaranteeConfirmResp.getGuaranteeConfirmId());

        // 担保确认订单查询（平台订单号）
        guaranteeConfirmResp = guaranteeConfirmExample.retrieveByOutOrderNo(guaranteeConfirmResp.getOutOrderNo());

        return guaranteeConfirmResp.getGuaranteeConfirmId();
    }

    /**
     * 担保确认
     *
     * @return 返回参数
     * @throws UpyztException 异常
     */
    public GuaranteeConfirmResp create() throws UpyztException {
        Map<String, Object> params = new HashMap<>();
        params.put("guarantee_payment_id", this.guaranteePaymentId);
        params.put("out_order_no", Main.generateRandomOutNo());
        params.put("sent_at", OffsetDateTime.now().toString());
        params.put("amount", 5);
        params.put("password", Upyzt.encryptField("pa55w0rd"));
        params.put("remark", "用于 SDK 示例测试");
        params.put("metadata", MockData.metadata());
        params.put("extra", MockData.extra());
        System.out.println("------- 担保确认 -------");
        GuaranteeConfirmResp resp = GuaranteeConfirm.create(params);
        System.out.println(resp);
        return resp;
    }

    /**
     * 担保确认订单查询（系统订单号）
     *
     * @return 返回参数
     * @throws UpyztException 异常
     */
    public GuaranteeConfirmResp retrieveById(String id) throws UpyztException {
        System.out.println("------- 担保确认订单查询（系统订单号） -------");
        GuaranteeConfirmResp resp = GuaranteeConfirm.retrieveById(id);
        System.out.println(resp);
        return resp;
    }

    /**
     * 担保确认订单查询（平台订单号）
     *
     * @return 返回参数
     * @throws UpyztException 异常
     */
    public GuaranteeConfirmResp retrieveByOutOrderNo(String outOrderNo) throws UpyztException {
        System.out.println("------- 担保确认订单查询（平台订单号） -------");
        GuaranteeConfirmResp resp = GuaranteeConfirm.retrieveByOutOrderNo(outOrderNo);
        System.out.println(resp);
        return resp;
    }

}
